// 打开数据库连接
const request = indexedDB.open("myTransDB", 2);
let db;

request.onerror = function (event) {
    console.log("数据库打开失败");
};

// 创建对象存储空间及索引
request.onupgradeneeded = function (event) {
    console.log("onupgradeneeded");
    db = event.target.result;

    // 创建对象存储空间
    const objectStore = db.createObjectStore("customers", { keyPath: "id" });

    // 创建索引（如果需要）
    objectStore.createIndex("name", "name", { unique: false });
    objectStore.createIndex("email", "email", { unique: true });

    // 数据库结构创建完毕后会触发 success 事件
    request.onsuccess = function (event) {
        console.log("数据库已创建");
    };
};

request.onsuccess = function (event) {
    db = event.target.result;
    // 执行事务
    doTransaction();
};

function doTransaction() {
    // 开启读写事务
    const transaction = db.transaction(["customers"], "readwrite");
    const objectStore = transaction.objectStore("customers");

    // 添加数据
    const addRequest = objectStore.add({ id: 2, name: "John Doe2", email: "john2@example.com" });

    addRequest.onerror = function (event) {
        console.log("数据添加失败");
    };

    addRequest.onsuccess = function (event) {
        console.log("数据添加成功");
    };

    // 查询数据
    const getRequest = objectStore.get(1);
    getRequest.onerror = function (event) {
        console.log("数据查询失败");
    };

    getRequest.onsuccess = function (event) {
        const result = event.target.result;
        console.log("查询结果:", result);
    };

    // 更新数据
    const updateRequest = objectStore.put({ id: 1, name: "John Smith", email: "john@example.com" });
    updateRequest.onerror = function (event) {
        console.log("数据更新失败");
    };

    updateRequest.onsuccess = function (event) {
        console.log("数据更新成功");
    };

    // 删除数据
    // const deleteRequest = objectStore.delete(1);
    // deleteRequest.onerror = function (event) {
    //     console.log("数据删除失败");
    // };
    // deleteRequest.onsuccess = function (event) {
    //     console.log("数据删除成功");
    // };

    // 事务完成
    transaction.oncomplete = function (event) {
        console.log("事务完成");
        // 关闭数据库连接（这一步也可以省略）
        // db.close();
    };

    transaction.onerror = function (event) {
        const error = event.target.error; // 获取错误对象
        console.log("事务错误:", error);

        console.log("错误码:", error.code);
        console.log("错误名称:", error.name);
        console.log("错误信息:", error.message);

        // 可能还有其他的错误属性可供查看

        // 如果需要进一步处理错误，可以抛出异常或执行其他操作
        // throw new Error("事务发生错误");
    };

}